<script setup lang="ts">
import { ref, nextTick } from "vue";
import { ElMessage } from "element-plus";
import {
  channelAllocateProductApiPost,
  channelDeleteAllocateProductApiDel,
  channelRelationProductPageApiPost,
} from "@/api/userMangement";
import { informationStore } from "./infomation";
import { storeToRefs } from "pinia";
import type { FormInstance, FormRules } from "element-plus";
import useInstance from "@/hooks/useInstance";
import { useComListData } from "@/store/list";
import clip from "@/utils/clipboard";
import { productLinkConfigListPost } from "@/api/allProduct";
import Clipboard from "clipboard";
const { listCollect } = storeToRefs(useComListData());

defineOptions({
  name: "addListAd",
});
const productOption = [
  {
    label: "是",
    value: 1,
  },
  {
    label: "否",
    value: 2,
  },
];
const { tableProp } = storeToRefs(informationStore());
const sonDialog = ref(false);
const sonEnvTitle = ref("关联产品");
const productFormRef = ref<FormInstance>();
const emit = defineEmits(["refresh"]);
const { global } = useInstance();
const showEnvAndScene = ref(false)
const relationData = reactive({
  params: {
    pageNum: 0,
    pageSize: 20,
    condition: {
      channelCodeList: [] as any,
      productCodeList: [],
    },
    orders: ["created_time desc"],
  },

  loading: false,
  list: [],
  rowData: {} as any,
  loadIng: false,
  total: 0,
});
const dialogBasic = ref({
  title: "关联产品",
  visible: false,
  width: 1200,
  height: 450,
  showFooter: false,
  marginTop: "5vh",
});
const addSupply = reactive<any>({
  channelCode: null, //  渠道编码
  channelProductName: null, //  渠道产品名称
  productCode: null, //  产品编码
  schemeCode: null, //  方案编码
  environmentCode: null, //   环境
  scenarioCode: null, //  场景
  enableReporting: null, //  是否开启上报
  reportingPlatformCode: null, //  上报平台
  enableGrantEquity: null, //  是否开启发放权益
});
const productFormRules = reactive<FormRules>({
  enableGrantEquity: [
    {
      required: true,
      trigger: "blur",
      message: "请选择是否开启发放权益",
    },
  ],
  reportingPlatformCode: [
    {
      required: true,
      trigger: "blur",
      message: "请选择上报平台",
    },
  ],
  enableReporting: [
    {
      required: true,
      trigger: "blur",
      message: "请选择是否开启上报",
    },
  ],
  productCode: [
    {
      required: true,
      trigger: "blur",
      message: "请选择渠道编码",
    },
  ],
  schemeCode: [
    {
      required: true,
      trigger: "blur",
      message: "请选择方案",
    },
  ],
  environmentCode: [
    {
      required: true,
      trigger: "blur",
      message: "请选择环境",
    },
  ],
  scenarioCode: [
    {
      required: true,
      trigger: "blur",
      message: "请选择场景",
    },
  ],
});
const sonCancel = () => {
  envAndSceneList.value = [];
  newSceneCodeList.value = [];
  showEnvAndScene.value = false
  Object.keys(addSupply).forEach((item: any) => delete addSupply[item]);
  sonDialog.value = false;
  productFormRef.value?.resetFields();
};
const envAdd = (type: string, row?: any) => {
  global.$resetForm(productFormRef.value, addSupply);

  if (type == "add") {
    sonEnvTitle.value = "关联产品";
    addSupply.channelCode = relationData.rowData.channelCode;
    addSupply.channelProductName = relationData.rowData.channelName;
  } else {
    global.$objCopy(addSupply, row);
    sonEnvTitle.value = "编辑环境";
  }
  sonDialog.value = true;
};
const sonConfirm = async () => {
  await productFormRef.value?.validate(async (isOk) => {
    if (isOk) {
      const res = await channelAllocateProductApiPost(addSupply);
      if (res.code == 20000) {
        ElMessage({
          type: "success",
          message: "渠道关联产品成功",
        });
        //
        sonCancel();
        // emit('refresh')
        relationData.params.pageNum = 1;
        relationData.params.pageSize = 20;
        getDataList();
      }
    } else {
      ElMessage({
        type: "error",
        message: "渠道关联产品失败 请重试！",
      });
    }
  });
};
//显示弹框
const show = async (type: string, row?: any, list?: any) => {
  relationData.rowData = row;

  relationData.params.condition.channelCodeList.length = 0;
  relationData.params.condition.channelCodeList.push(row.channelCode);
  getDataList();
  dialogBasic.value.visible = true;
};
const getDataList = async () => {
  try {
    relationData.loadIng = true;
    const res = await channelRelationProductPageApiPost(relationData.params);
    if (res.code == 20000 && res.data.records) {
      relationData.list = res.data.records.map((item: any) => {
        return {
          ...item,
          enableReporting: item.enableReporting == 1 ? "是" : "否", //  是否开启上报
          enableGrantEquity: item.enableGrantEquity == 1 ? "是" : "否", //  是否开启发放权益
          environmentName: item.environmentCode + "-" + item.environmentName,
          scenarioName: item.scenarioCode + "-" + item.scenarioName,
        };
      });
      relationData.loadIng = false;
      relationData.total = res.data.total;
    } else {
      relationData.list.length = 0;
      relationData.loadIng = false;
      relationData.total = res.data.total;
    }
  } catch (error) {
    relationData.loadIng = false;
  }
};
const onClose = () => {
  dialogBasic.value.visible = false;
};
const onConfirm = async () => {
  try {
    const res = await channelAllocateProductApiPost({});
    if (res.code == 20000) {
      onClose();
      emit("refresh");
      ElMessage({
        type: "success",
        message: "渠道产品分配成功",
      });
    }
  } catch (error) {
    ElMessage({
      type: "warning",
      message: "渠道产品分配失败 请重试！",
    });
  }
};
const btnCopy = () => {
  console.log("====>>>btn");
  var clipboard = new Clipboard(".content-bootom-copy");
  clipboard.on("success", (e) => {
    console.log(e, "成功");

    clipboard.destroy();
  });
  // 复制失败执行的回调，可选
  clipboard.on("error", (e) => {
    console.log("失败");
  });
};
const LinkBtn = async (row: any, event: any) => {
  if (row.orderLink) {
    clip(row.orderLink, event);
  } else {
    ElMessage({
      type: "error",
      message: `链接未生成 请检查 产品链接基础配置是否对该产品 ${row.productName}的配置正确 或删除该产品重新创建`,
    });
  }
};
const delBtn = async (row: any) => {
  const flag = await global.$myconfirm(
    `是否确定删除该关联产品？  ${row.productName}`
  );
  if (flag) {
    const res = await channelDeleteAllocateProductApiDel({ id: row.id });
    console.log(res.data);
    if (res.code == 20000) {
      ElMessage({
        type: "success",
        message: "数据删除成功",
      });
      relationData.params.pageNum = 1;
      relationData.params.pageSize = 20;
      getDataList();
    } else {
      ElMessage({
        type: "error",
        message: "数据删除失败",
      });
    }
  }
};

const showReportingPlatformCode = (e: any) => {
  console.log(e);
  if (e == 2) {
    addSupply.reportingPlatformCode = null;
  }
};
const handPage = (val: { pageNum: number; pageSize: number }) => {
  relationData.params.pageNum = val.pageNum;
  relationData.params.pageSize = val.pageSize;
  getDataList();
};
defineExpose({
  show,
});
/* 筛选产品基础链接的环境和场景 */
const productChange = (item: any) => {
  console.log(item, 'type');

  let arr = []
  if (!item) {
    addSupply.schemeCode = null
    showEnvAndScene.value = false

    addSupply.scenarioCode = null;
    addSupply.environmentCode = null;
    // 恢复
  } else {
    searchProductLinkList(item);
    addSupply.scenarioCode = null;
    addSupply.environmentCode = null;

    arr = listCollect.value.productList.filter(it => it.productCode == item)
    console.log(arr[0]);
    addSupply.schemeCode = arr[0].schemeCode
    // 权益编码
    if (arr[0].productType == 2) {
      // 要
      showEnvAndScene.value = true

    } else {
      // 不要
      showEnvAndScene.value = false
      addSupply.scenarioCode = null;
      addSupply.environmentCode = null;
    }
  }
};
const envAndSceneList = ref<any>([]);
const newSceneCodeList = ref<any>([]);
let result = {};
const transFormArr = (data: any) => {
  result = {};
  // 遍历数据并填充映射
  data.forEach((item: any) => {
    const envKey = item.environment;
    const envName = item.environmentName;

    if (!result[envKey]) {
      result[envKey] = {
        key: envKey,
        name: envName,
        value: [],
      };
    }

    const scenarioKey = item.scenario;
    const scenarioName = item.scenarioName;

    // 检查是否已经存在相同的 scenario
    const existingScenario = result[envKey].value.find(
      (scenario) => scenario.key === scenarioKey
    );
    if (!existingScenario) {
      result[envKey].value.push({
        key: scenarioKey,
        name: scenarioName,
      });
    }
  });

  // 将映射转换为数组
  const finalResult = Object.values(result);
  console.log(finalResult);
  envAndSceneList.value = finalResult;
};
const searchProductLinkList = async (item: string) => {
  envAndSceneList.value = [];
  newSceneCodeList.value = [];
  const res = await productLinkConfigListPost({
    productCode: item,
  });
  // 如果只有一条数据 如果多条数据 如果 没有查询到

  if (res.code == 20000 && !res.data) {
    if (showEnvAndScene.value) {
      return ElMessage({
        type: "warning",
        message: "该产品无基础链接 请添加",
      });
    } else {
      return
    }
  }
  if (res.code == 20000 && res.data && res.data.length == 1) {
    transFormArr(res.data);
    addSupply.scenarioCode = res.data[0]?.scenario;
    addSupply.environmentCode = res.data[0]?.environment;
  } else {
    transFormArr(res.data);
  }
};
const environmentCodeChange = (item: any) => {
  addSupply.scenarioCode = null;
  newSceneCodeList.value = [];
  const arr = envAndSceneList.value.filter((it: any) => it.key == item);
  newSceneCodeList.value = arr[0]?.value;
};
</script>

<template>
  <SysDialog :title="dialogBasic.title" :width="dialogBasic.width" :height="dialogBasic.height"
    :show-footer="dialogBasic.showFooter" :visible="dialogBasic.visible" :margin-top="dialogBasic.marginTop"
    @on-close="onClose" @on-confirm="onConfirm">
    <template v-slot:content>
      <div class="content-table">
        <div class="header">
          <div class="left">
            <el-row>
              <el-col :xs="24" :sm="24" :sd="24" :lg="8" :xl="8">渠道编码 ： {{ relationData.rowData.channelCode }}</el-col>
              <el-col :xs="24" :sm="24" :sd="24" :lg="8" :xl="8">渠道Key ： {{ relationData.rowData.channelKey }}</el-col>
              <el-col :xs="24" :sm="24" :sd="24" :lg="8" :xl="8">渠道名称 ： {{ relationData.rowData.channelName }}</el-col>
            </el-row>
          </div>

          <div class="right">
            <el-button type="success" @click="envAdd('add')">新增</el-button>
          </div>
        </div>
        <div class="table">
          <OnlyTable ref="onlyTableRef" class="card-2" :tableProps="tableProp" :pageTotal="relationData.total"
            @get-page="handPage" :tableData="relationData.list" :loading="relationData.loadIng">
            <template #handle="scope">
              <el-button type="success" @click="LinkBtn(scope.row, $event)" id="myLink" link
                size="small">生成链接</el-button>
              <el-button type="danger" @click="delBtn(scope.row)" link size="small">删除</el-button>
            </template>
          </OnlyTable>
        </div>
      </div>
    </template>
  </SysDialog>
  <!-- 新增产品链接 -->
  <el-dialog v-model="sonDialog" top="5vh" width="500" :title="sonEnvTitle" append-to-body>
    <el-form ref="productFormRef" :model="addSupply" :rules="productFormRules" label-width="140px"
      class="demo1-ruleForm" status-icon>
      <el-form-item label="产品编码" prop="productCode">
        <el-select v-model="addSupply.productCode" @change="productChange" placeholder="请选择产品编码" value-key="id"
          filterable clearable>
          <el-option v-for="item in listCollect.productList" :key="item.key" :label="item.value" :value="item.key" />
        </el-select>
      </el-form-item>

      <el-form-item label="方案编码" prop="schemeCode">
        <el-select v-model="addSupply.schemeCode" placeholder="请选择方案编码" filterable>
          <el-option v-for="item in listCollect.equitySchemeList" :key="item.key" :label="item.value"
            :value="item.key" />
        </el-select>
      </el-form-item>

      <el-form-item label="环境" prop="environmentCode" v-if="showEnvAndScene">
        <el-select v-model="addSupply.environmentCode" placeholder="请选择环境" filterable clearable
          @change="environmentCodeChange">
          <el-option v-for="item in envAndSceneList" :key="item.key" :label="`${item.key} - ${item.name}`"
            :value="item.key" />
        </el-select>
      </el-form-item>
      <el-form-item label="场景" prop="scenarioCode" v-if="showEnvAndScene">
        <el-select v-model="addSupply.scenarioCode" placeholder="请选择场景" filterable>
          <el-option v-for="item in newSceneCodeList" :key="item.key" :label="`${item.key} - ${item.name}`"
            :value="item.key" />
        </el-select>
      </el-form-item>
      <el-form-item label="是否开启上报" prop="enableReporting">
        <el-select v-model="addSupply.enableReporting" placeholder="请选择是否开启上报" @change="showReportingPlatformCode"
          filterable>
          <el-option v-for="item in productOption" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <template v-if="addSupply.enableReporting == 1">
        <el-form-item label="上报平台" prop="reportingPlatformCode">
          <el-select v-model="addSupply.reportingPlatformCode" placeholder="请选择上报平台" filterable>
            <el-option v-for="item in listCollect.reportingPlatformCodeList" :key="item.value" :label="item.label"
              :value="item.value" />
          </el-select>
        </el-form-item>
      </template>
      <el-form-item label="是否开启发放权益" prop="enableGrantEquity">
        <el-select v-model="addSupply.enableGrantEquity" placeholder="请选择是否开启发放权益" filterable>
          <el-option v-for="item in productOption" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="sonCancel">取消</el-button>
        <el-button type="primary" @click="sonConfirm"> 确认 </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style lang="scss" scoped>
.content-table {
  height: 500px;
}

.header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 15px;

  .left {
    flex-grow: 1;
  }
}

.demo1-ruleForm {
  height: 400px;
}
</style>
